const optionsDefault = {
    key: 'id',
    parentKey: 'parentId',
    children: 'children'
};

/**
 * @description 数组转树形结构
 * @param {Array} array 需要转换的数组
 * @param {Object} options 配置项
 * @returns {Array}
 */
function toArrayTree(array, options) {
    let result = [];
    let option = Object.assign({}, optionsDefault, options);
    let optKey = option.key; // 主键名称
    let optParentKey = option.parentKey; // 父级主键名称
    let optChildren = option.children; // 子节点属性
    let keys = {};
    let treeMap = {}; // 存储所有节点的引用
    try {
        array.forEach(item => {
            keys[item[optKey]] = true;
        });

        array.forEach(item => {
            let id = item[optKey];
            let parentKey = item[optParentKey];
            let treeData = item;

            treeMap[id] = treeMap[id] || []
            treeData[optKey] = id
            treeData[optParentKey] = parentKey

            if (id === parentKey) {
                parentKey = null
            }

            treeMap[parentKey] = treeMap[parentKey] || []
            treeMap[parentKey].push(treeData)
            treeData[optChildren] = treeMap[id]

            if (!keys[parentKey]) {
                result.push(treeData)
            }
        });
    } catch (error) {
        throw new Error(error);
    }
    return result;
}

module.exports = toArrayTree;